package com.hjw.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Administrator
 * @创建时间：2025-04-11
 * @文件名称：satoken_sobuk - com.hjw.utils
 */
@Slf4j
@Component
public class Utils {

    private static final ObjectMapper objectMapper = new ObjectMapper(); ;

    public static String reqSuccess(String msg,Object data){
        Result result = new Result(msg, data);

        try {
            return objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            return "数据序列化失败";
        }

    }
    public static String reqOut(int code,String msg,Object data) {
        Result result = new Result(code, msg, data);
        try {
            return objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            return "数据序列化失败";
        }
    }

    public static String highlightText(String input, String key) {
        if (input == null || key == null || key.isEmpty()) {
            return input;
        }
        String highlightStart = "<span style='color:red;'>";
        String highlightEnd = "</span>";
        // 编译正则表达式，忽略大小写
        Pattern pattern = Pattern.compile(Pattern.quote(key), Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);
        StringBuffer sb = new StringBuffer();
        // 查找匹配项并替换
        while (matcher.find()) {
            matcher.appendReplacement(sb, highlightStart + matcher.group() + highlightEnd);
        }
        // 添加剩余部分
        matcher.appendTail(sb);
        return sb.toString();
    }

}
